<?php

namespace app\model;

use think\Model;

class Product extends Model
{
    public function saveData(): array
    {
        $param = request()->post();
        if (empty($param)) throw new \Exception("参数错误", 7001);
        $param['content'] = htmlspecialchars($param['content']);
        if (in_array($param['type'], [1, 3]) && empty($param['user_text'])) throw new \Exception("请填写产品补充信息", 7002);
        if ($param['type'] == 1) $param['user_text'] = json_encode($param['user_text'], 320);
        //判断输入的是否是域名
        if ($param['type'] == 3 && !filter_var($param['user_text'], FILTER_VALIDATE_URL)) {
            throw new \Exception("请输入正确的域名", 7003);
        }
        $this->exists(!empty($param['id']))->save($param);
        return $this->toArray();
    }

    public function pageData(): array
    {
        $param = request()->param();
        $data = $this->when(!empty($param['name']), function ($query) use ($param) {
            $query->whereLike("name", "%{$param['name']}%");
        })->when(!empty($param['type']), function ($query) use ($param) {
            $query->whereIn("type", $param['type']);
        })->where(['is_del' => 1])->order(['create_time' => 'desc'])->paginate(['list_rows' => $param['pageSize'] ?? 30, 'page' => $param['page'] ?? 1])->toArray();
        return ['lst' => $data['data'], 'total' => $data['total']];
    }

    public function detail(): array
    {
        $data = $this->findOrFail(request()->param('id'))->toArray();
        $data['content'] = htmlspecialchars_decode($data['content']);
        if ($data['type'] == 1) {
//            $data->a = 1;
            $data['user_text'] = json_decode($data['user_text'], true);
        }
        return $data;
    }

    public function del()
    {
        $id = request()->param("id");
        return $this->where(['id' => $id])->update(['is_del' => 0]);
    }

    public function getProductList(): array
    {
        return $this->where(['is_del' => 1])->select()->toArray();
    }
}
